package com.aishare.qicaitaoke.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 作者luwenming
 * 时间2018/1/31
 */

public class NetworkUtils {

    private static final int NETWORK_NONE = -1;

    private static final int NETWORK_MOBILE = 0;

    private static final int NETWORK_WIFI = 1;

    public static int getNetWorkState(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if(activeNetworkInfo !=null && activeNetworkInfo.isConnected()){
            if(activeNetworkInfo.getType() == connectivityManager.TYPE_WIFI){
                return  NETWORK_WIFI;
            }else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)){
                return NETWORK_MOBILE;
            }
        }else {
            return  NETWORK_NONE;
        }
        return NETWORK_NONE;
    }

    /**
     * 网络是否可用
     * @param context
     * @return
     */
    public static boolean isNetConnected(Context context){
      ConnectivityManager netManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert netManager != null;
        NetworkInfo networkInfo = netManager.getActiveNetworkInfo();
      if(networkInfo == null ){
          return networkInfo != null;
      }else {
          return  networkInfo.isAvailable() && networkInfo.isConnected();
      }
    }

    public static boolean isNetWorkConnected(Context context,int typeMobile ){
        if(!isNetConnected(context)){
            return false;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connectivityManager != null;
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(typeMobile);
        if(networkInfo !=null){
            return networkInfo.isConnected()&&networkInfo.isAvailable();
        }else {
            return false;
        }
    }

    public static boolean isPhoneNetConnected(Context context){
       int typeMobile = ConnectivityManager.TYPE_MOBILE;
       return isNetWorkConnected(context,typeMobile);
    }

    public static boolean isWifiNetConnected(Context context){
        int typeMobile = ConnectivityManager.TYPE_WIFI;
        return isNetWorkConnected(context,typeMobile);
    }
}
